package com.jfree.zk.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.LockInternalsDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 包装InterProcessMutex
 * @author wangjian
 * @date 2019/7/16 17:43
 */
public class InterProcessMutexLcok extends InterProcessMutex{

    public static Logger log = LoggerFactory.getLogger(InterProcessMutexLcok.class);

    public InterProcessMutexLcok(CuratorFramework client, String path) {
        super(client, path);
    }

    public InterProcessMutexLcok(CuratorFramework client, String path, LockInternalsDriver driver) {
        super(client, path, driver);
    }

    /**
     * 获取锁
     * @param time
     * @param unit
     * @param retry
     */
    public void acquireLock(Integer time,TimeUnit unit,Integer retry) {
        int flag = 0;
        try {
            while (!super.acquire(time, unit)) {
                flag++;
                if (flag > retry-1) {   //重试
                    break;
                }
            }
        } catch (Exception e) {
            log.error("distributed lock acquire exception=" + e);
        }
        if (flag > 1) {
            log.info("Thread:" + Thread.currentThread().getId() + " acquire distributed lock  busy");
        } else {
            log.info("Thread:" + Thread.currentThread().getId() + " acquire distributed lock  success");
        }
    }
    /**
     * 释放锁
     */
    public void releaseLock() {
        try {
            if (super.isAcquiredInThisProcess()) {
                super.release();
                log.info("Thread:" + Thread.currentThread().getId() + " release distributed lock  success");
            }
        } catch (Exception e) {
            log.error("Thread:" + Thread.currentThread().getId() + " release distributed lock  exception=" + e);
        }
    }
}
